import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

// 使用插件
Vue.use(VueRouter)

import route from './route'

// 配置路由
let router = new VueRouter({
    routes: route,
    scrollBehavior(to, from, savedPosition){
        return { x: 0, y: 0 }
    }
})

// 全局前置路由守卫
router.beforeEach( async (to,from,next)=>{
    // 已经登陆
    if(store.state.user.token){
        if(to.path == "/login" || to.path == "/register"){
            next("/")
        }else{
            if(store.state.user.userInfo.name){
                next()
            }else{
                try {
                    await store.dispatch("getUserInfo")
                    next()
                } catch (error) {
                    await store.dispatch("userLogout")
                    next("/login")
                }
            }
        }
    } else{
        let toPath = to.path
        next()
    }
})

export default router